package cn.stylefeng.guns.modular.gridsystem.timer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.core.timer.TimerTaskRunner;
import cn.stylefeng.guns.modular.gridsystem.constants.GatewayTaskTypeConstant;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGateway;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGatewayConfig;
import cn.stylefeng.guns.modular.gridsystem.entity.CollectionModel;
import cn.stylefeng.guns.modular.gridsystem.entity.GatewayFirmware;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayConfigMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.CollectionModelMapper;
import cn.stylefeng.guns.modular.gridsystem.service.GatewayTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 测试网关任务下发定时任务
 *
 * @author zxw 2022/11/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TestGatewayTaskRunner implements TimerTaskRunner {

    private final GatewayTaskService taskService;

    private final BizGatewayMapper gatewayMapper;

    private final BizGatewayConfigMapper gatewayConfigMapper;

    private final CollectionModelMapper collectionModelMapper;

    private int minuteCounter = 0;

    private int versionNumber = 300;

    public static final String DEVICE_CODE = "db7919d6d81bb99f159f0e8f44981817";

    private int waitMins = 0;

    private int resetMins = 15;

    private int poweroffMins = 10;

    private boolean isRandom = true;

    private Long wavFleId1 = 1591334467943870465L;

    private Long wavFleId2 = 1591334714833186818L;

    private Long applicationFileId = 1591978672840052738L;

    private Long agentFileId = 1591979192182968321L;

    public static final Integer reset_wait_number = 15;

    public static final Integer power_off_wait_number = 10;

    @Override
    public void action() {

        Random random = new Random();

        int x = isRandom ? random.nextInt(100) % 6 : 5;

        if (x == 5) {
            isRandom = false;
        }

        // 查询网关ID
        Integer gatewayId = gatewayMapper.selectOne(new LambdaQueryWrapper<BizGateway>()
                .eq(BizGateway::getGatewayCode, DEVICE_CODE)
                .last("limit 1")).getId();

        List<Integer> gatewayIds = new ArrayList<>();
        gatewayIds.add(getGateway().getId());

        if (x == 0) {

            // 更新配置
            log.info("=======>>>    下发更新配置任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
            BizGatewayConfig audioWavSize = gatewayConfigMapper.selectOne(new LambdaQueryWrapper<BizGatewayConfig>().eq(BizGatewayConfig::getGatewayId, gatewayId).eq(BizGatewayConfig::getGatewayConfigCode, "audioWavSize").last("limit 1"));
            if (ObjectUtil.isEmpty(audioWavSize)) {
                log.warn("=======>>>    当前网关不存在code为【audioWavSize】配置项");
            } else {
                audioWavSize.setConfigValue(String.valueOf(Integer.parseInt(audioWavSize.getConfigValue()) + minuteCounter));
                gatewayConfigMapper.updateById(audioWavSize);
            }

            BizGatewayConfig soundmakerVolumeActiveVoice = gatewayConfigMapper.selectOne(new LambdaQueryWrapper<BizGatewayConfig>().eq(BizGatewayConfig::getGatewayId, gatewayId).eq(BizGatewayConfig::getGatewayConfigCode, "soundmakerVolumeActiveVoice").last("limit 1"));
            if (ObjectUtil.isEmpty(audioWavSize)) {
                log.warn("=======>>>    当前网关不存在code为【soundmakerVolumeActiveVoice】配置项");
            } else {
                soundmakerVolumeActiveVoice.setConfigValue(String.valueOf(Integer.parseInt(soundmakerVolumeActiveVoice.getConfigValue()) + 1));
                gatewayConfigMapper.updateById(soundmakerVolumeActiveVoice);
            }

            BizGatewayConfig audiocaptureSerialName = gatewayConfigMapper.selectOne(new LambdaQueryWrapper<BizGatewayConfig>().eq(BizGatewayConfig::getGatewayId, gatewayId).eq(BizGatewayConfig::getGatewayConfigCode, "audiocaptureSerialName").last("limit 1"));
            if (ObjectUtil.isEmpty(audioWavSize)) {
                log.warn("=======>>>    当前网关不存在code为【audiocaptureSerialName】配置项");
            } else {
                audiocaptureSerialName.setConfigValue(audiocaptureSerialName.getConfigValue() + "absse");
                gatewayConfigMapper.updateById(audiocaptureSerialName);
            }

            taskService.add(GatewayTaskTypeConstant.UPDATE_CONFIG, gatewayIds, null);

        } else if (x == 1) {

            // 更新固件
            GatewayFirmware firmware = GatewayFirmware.builder()
                    .gatewayIds("[" + gatewayId + "]")
                    .applicationFileId(applicationFileId)
                    .agentFileId(agentFileId)
                    .accessFileId(wavFleId1)
                    .versionNumber(versionNumber++)
                    .versionName(" test version")
                    .updateRemark(" update remark")
                    .build();
            taskService.add(GatewayTaskTypeConstant.UPDATE_FIRMWARE, gatewayIds, JSONUtil.toJsonStr(firmware));
            log.info("=======>>>    下发固件更新任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
            //下发更新固件任务后等待1分半钟再下发重启任务
            ThreadUtil.safeSleep(90000);
            // 重启程序
            if (resetMins == reset_wait_number - 1) {

                log.info("=======>>>    下发重启任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
                taskService.add(GatewayTaskTypeConstant.RESET, gatewayIds, null);

            } else {

                if (resetMins == 0) {
                    resetMins = reset_wait_number;
                    minuteCounter++;
                    isRandom = true;
                }
                log.info("=======>>>    重启等待次数是：{}", resetMins);
                return;
            }

        } else if (x == 2) {

            // 注册模型
            log.info("=======>>>    下发注册模型任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
            Map<String, Object> map = new HashMap<>();
            map.put("faultName", "test regiest mode " + minuteCounter);
            map.put("failureLevel", "0");
            map.put("expectGroupId", "1");
            map.put("expectAccessToken", "1");
            map.put("fileIds", wavFleId1 + "," + wavFleId2 + "" + wavFleId2);
            taskService.add(GatewayTaskTypeConstant.REGISTER_MODEL, gatewayIds, JSONUtil.toJsonStr(map));

        } else if (x == 3) {

            // 同步模型
            log.info("=======>>>    下发同步模型任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
            collectionModelMapper.delete(new LambdaQueryWrapper<CollectionModel>().eq(CollectionModel::getGatewayId, gatewayId));
            taskService.add(GatewayTaskTypeConstant.SYNC_MODEL, gatewayIds, null);

        } else if (x == 4) {

            // 上报最新文件
            log.info("=======>>>    下发上服最新文件任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
            Map<String, Object> map = new HashMap<>();
            map.put("micRouter", "5");
            taskService.add(GatewayTaskTypeConstant.UPLOAD_NEW_FILE, gatewayIds, JSONUtil.toJsonStr(map));


        } else if (x == 5) {
            resetMins--;
            // 重启程序
            if (resetMins == reset_wait_number - 1) {

                log.info("=======>>>    下发重启任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
                taskService.add(GatewayTaskTypeConstant.RESET, gatewayIds, null);

            } else {

                if (resetMins == 0) {
                    resetMins = reset_wait_number;
                    minuteCounter++;
                    isRandom = true;
                }
                log.info("=======>>>    重启等待次数是：{}", resetMins);
                return;

            }
        } /*else {
            // 重启硬件
            poweroffMins--;
            if (poweroffMins == power_off_wait_number - 1) {
                log.info("=======>>>    下发重启硬件任务，当前时间是：{}，分钟计数器的值是：{}", DateTime.now(), minuteCounter);
            } else {
                if (poweroffMins == 0) {
                    poweroffMins = power_off_wait_number;
                    minuteCounter++;
                }
                log.info("=======>>>    重启硬件等待次数是：{}", poweroffMins);
                return;
            }
        }*/

        if (x != 5) {
            minuteCounter++;
        }

    }

    private BizGateway getGateway() {
        return gatewayMapper.selectOne(new LambdaQueryWrapper<BizGateway>()
                .eq(BizGateway::getGatewayCode, DEVICE_CODE)
                .last("limit 1"));
    }

}
